package com.chaopei.base2;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author Corday 天涯
 * @Date 2022/3/6 22:22
 * 线程池的用法
 */
public class MyThreadPool {
    private static Integer page = 1;

    public static void main(String[] args) {
//        创建线程池,Executors创建线程池对象与Executor是ExecutorService的接口
//        定义了execute方法
        ExecutorService es = Executors.newFixedThreadPool(10);
        while (true) {
            if (page <= 100) {
                es.execute(new Runnable() {
                    //模拟抓取网页
                    @Override
                    public void run() {
                        System.out.println("抓取了第:" + page + "个网页");
                        page++;
                    }
                });
            } else {//强制向下转型,获取线程更多的状态
                ThreadPoolExecutor tpe = (ThreadPoolExecutor) es;
                if (tpe.getActiveCount() == 0) {
                    es.shutdown();
                    System.out.println("任务结束");
                    break;//跳出循环
                }
            }
            try {//暂停一会
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }//while
        //创建多种类型线程池对象
        ExecutorService es1 = Executors.newCachedThreadPool();
        ExecutorService es2 = Executors.newFixedThreadPool(10);
        ExecutorService es3 = Executors.newScheduledThreadPool(20);
        ExecutorService es4 = Executors.newSingleThreadScheduledExecutor();
    }//main
}
